package org.bagou.xiangs.framework_mvvm.newer_databinding

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.databinding.library.baseAdapters.BR
import androidx.recyclerview.widget.RecyclerView
import org.bagou.xiangs.framework_mvvm.R

class DataBindingNewMvvmAdapter : RecyclerView.Adapter<DataBindingNewMvvmAdapter.MvvmViewHolder>() {

    private var dataList: ArrayList<WechatItem>? = ArrayList()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MvvmViewHolder {
        val binding = DataBindingUtil.inflate<ViewDataBinding>(
            LayoutInflater.from(parent.context),
            R.layout.item_user_new_databinding, parent, false
        )
        return MvvmViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return dataList!!.size
    }

    override fun onBindViewHolder(holder: MvvmViewHolder, position: Int) {
        onViewLayoutSet(holder, position)
        holder.binding.setVariable(BR.infoItem, dataList!![position])
    }


    fun addData(data: List<WechatItem>) {
        dataList?.addAll(data)
        notifyDataSetChanged()
    }

    inner class MvvmViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root)

    // 设置控件样式
    private fun onViewLayoutSet(holder: MvvmViewHolder, position: Int) {
        val layoutParams: ViewGroup.LayoutParams = holder.binding.root.layoutParams
        when (position) {
            0 -> {
                (layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin = 30
                (layoutParams as? ViewGroup.MarginLayoutParams)?.bottomMargin = 30
            }
            itemCount - 1 -> (layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin = 30
            else -> (layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin = 1
        }
        holder.binding.root.layoutParams = layoutParams
    }
}


